import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { userService } from '@/service/userService';
import { storageService } from '@/service';
import { UserProfile } from '@/types/user';


interface AuthContextType {
  user: UserProfile | null;
  isAuthenticated: boolean;
  isOffline: boolean;
  isLoading: boolean;
  login: (token: string, userInfo: UserProfile) => void;
  logout: () => void;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<UserProfile | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isOffline, setIsOffline] = useState(false);


  useEffect(() => {
    // 初始化时检查本地存储中是否有用户信息
    const checkAuth = async () => {
      const token = storageService.getToken();
      const storedUser = storageService.getUser();

      if (token && storedUser) {
        // 验证token有效性

        const response = await userService.getCurrentUser();
        if (response.code === 0) {
          setUser((response as { code: 0; data: UserProfile }).data);
          setIsOffline(false);
        } else if (response.code === 1200) {
          // Token无效或过期
          storageService.clearAuth();
          setIsOffline(false);
        } else {
          setIsOffline(true);
        }
      }

      setIsLoading(false);
    };

    checkAuth();
  }, [window.location.href]); 

  // 登录
  const login = (token: string, userInfo: UserProfile) => {
    storageService.setToken(token);
    storageService.setUser(userInfo);
    setUser(userInfo);
  };

  // 登出
  const logout = () => {
    storageService.clearAuth();
    setUser(null);
  };

  return (
    <AuthContext.Provider
      value={{
        user,
        isAuthenticated: !!user,
        isOffline,
        isLoading,
        login,
        logout,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
}